﻿//#define Test
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Owin.Hosting;
using MQTT.Server.Host.Controller;
using MQTT.Server.Host.Entity;
using MQTT.Server.Host.WebAPI;
using Newtonsoft.Json;
using Server.Library.MQTT;

namespace MQTT.Server.Host
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        private ObservableCollection<DeviceEntity> devices = new ObservableCollection<DeviceEntity>();
        private ObservableCollection<DataNodeEntity> dataNodes = new ObservableCollection<DataNodeEntity>();

        public const string DataTopic = "$kv";
        public const string WarningInfoTopic = "$wi";

        public MainWindow()
        {
            InitializeComponent();

            // 设置数据绑定
            lvDevices.ItemsSource = devices;
            lvDataNodes.ItemsSource = dataNodes;


            // 判断是否多IP
            var hostAddresses = Dns.GetHostAddresses(Dns.GetHostName());
            List<string> ipList = new List<string>();
            foreach (var address in hostAddresses)
            {
                if (address.AddressFamily == AddressFamily.InterNetwork)
                {
                    ipList.Add(address.MapToIPv4().ToString());
                }
            }
            if (ipList.Count == 0)
            {
                MessageBox.Show("未在该计算机获取到有效Ip", "错误：程序启动失败", MessageBoxButton.OK, MessageBoxImage.Error);
                Environment.Exit(0);
            }

            if (ipList.Count > 1)
            {
                MessageBox.Show("检测到该计算机有多个Ip地址，请选择你需要的ip地址");
                WinSelectIp win = new WinSelectIp(ipList);
                win.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                if (win.ShowDialog() == true)
                {
                    App.ServerIp = win.Ip;
                }
            }
            else
            {
                App.ServerIp = ipList[0];
            }

            // 启动webapi服务

            Thread t = new Thread(() =>
            {
                try
                {
#if Test
                    string baseAddress = $"http://localhost:9000/";

#else
                    string baseAddress = $"http://{App.ServerIp}:9000/";

#endif

                    WebApp.Start<Startup>(baseAddress);
                }
                catch (Exception e)
                {
                    MessageBox.Show("请使用管理员身份启动", "错误：程序启动失败", MessageBoxButton.OK, MessageBoxImage.Error);
                    Environment.Exit(0);
                }

            });
            t.IsBackground = true;
            t.Start();


            // 设置显示的数据
            txtMqttServerIpAdd.Text = App.ServerIp;
            txtMqttServerPort.Text = App.MQTTServerPort.ToString();

        }

        private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            // 获取所有的设备
            GetDevices();

            // 启动mqtt服务器

            Start(App.ServerIp, App.MQTTServerPort);
        }

        // 添加设备按钮
        private void BtnDeviceAdd_OnClick(object sender, RoutedEventArgs e)
        {
            WinAddDevice win = new WinAddDevice();
            win.Owner = this;
            win.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            if (win.ShowDialog() == true)
            {
                GetDevices();
            }
        }

        /// <summary>
        /// 获取所有设备
        /// </summary>
        private void GetDevices()
        {
            var deviceEntities = DataController.GetDevices();
            devices.Clear();
            foreach (var deviceEntity in deviceEntities)
            {
                devices.Add(deviceEntity);
            }
        }


        private void LvDevices_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var device = lvDevices.SelectedItem as DeviceEntity;
            if (device == null)
            {
                btnDeviceRemove.IsEnabled = false;
                return;
            }
            btnDeviceRemove.IsEnabled = true;
            List<DataNodeEntity> nodes = DataController.GetDataNodes(device.Id);
            dataNodes.Clear();
            foreach (var node in nodes)
            {
                dataNodes.Add(node);
            }
        }

        /// <summary>
        /// 移除设备功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDeviceRemove_OnClick(object sender, RoutedEventArgs e)
        {
            var device = lvDevices.SelectedItem as DeviceEntity;
            if (device == null)
            {
                return;
            }

            if (MessageBox.Show("是否删除该设备？", "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                // 从数据库中移除
                // 从列表中移除
                int i = DataController.RemoveDevice(device.Id);
                if (i > 0)
                {
                    devices.Remove(device);
                }
            }
        }

        public void Start(string ip, int port)
        {
            App.server = new MQTTServerEntity(ip, port);
            App.server.ClientConnected += id =>
            {
                // 修改在线状态
                try
                {
                    int deviceId = Convert.ToInt32(id);
                    DataController.SetDeviceIsOnline(deviceId, true);
                    var device = devices.FirstOrDefault(p => p.Id == deviceId);
                    if (device != null)
                    {
                        Dispatcher.Invoke(new Action(() =>
                        {
                            device.IsOnline = 1;

                        }));
                    }
                }
                catch (Exception e)
                {

                }
            };

            App.server.ClientDisConnected += id =>
            {
                // 修改在线状态
                try
                {
                    int deviceId = Convert.ToInt32(id);
                    DataController.SetDeviceIsOnline(deviceId, false);
                    var device = devices.FirstOrDefault(p => p.Id == deviceId);
                    if (device != null)
                    {
                        Dispatcher.Invoke(new Action(() =>
                        {
                            device.IsOnline = 0;

                        }));

                    }
                }
                catch (Exception e)
                {

                }

            };
            App.server.ClientMessageReceived += (id, topic, msg) =>
            {
                // 解析数据 并插入数据库

                // 判断主题是否符合
                if (topic.ToLower().Equals(DataTopic))
                {
                    // 解析数据
                    var mqttDataEntity = JsonConvert.DeserializeObject<MqttDataEntity>(msg);
                    // 根据设备id及数据标识获取数据类型
                    foreach (var tagEntity in mqttDataEntity.D)
                    {
                        int[] tagIdAndDataTypeId = DataController.GetDataTagIdAndDataTypeId(Convert.ToInt32(id), tagEntity.Tag);
                        var dataTagId = tagIdAndDataTypeId[0];
                        var dataTypeId = tagIdAndDataTypeId[1];

                        if (dataTagId == 0)
                        {
                            continue;
                        }

                        double value = 0.0;
                        // 根据不同的数据类型进行转换
                        // 序号代表的数据：
                        // 1温度  0-5V   -30-80
                        // 2湿度      4-20ma  0-100
                        // 3烟雾
                        // 4PM25     0-5V   0-1000
                        // 5PM10     0-5V   0-1000

                        switch (dataTypeId)
                        {
                            case 1:
                                //value = (tagEntity.Value - 32767) / 32767 * 10 / 5 * 110 - 30;
                                value = tagEntity.Value / 65535 * 110 - 30;
                                break;
                            case 2:
                                //value = (tagEntity.Value - 32767) / 32767 * 10 / 16 * 100;
                                value = tagEntity.Value / 65535 * 100;
                                break;
                            case 3:
                            case 4:
                                value = tagEntity.Value / 65535 * 1000;
                                break;
                            case 5:
                                value = tagEntity.Value;
                                break;

                        }

                        // 插入数据
                        DataController.AddData(value, dataTagId);
                    }
                }
                else if (topic.ToLower().Equals(WarningInfoTopic))
                {
                    // 接收到报警信息
                    // 解析数据
                    // 插入报警信息到数据库
                    var warningInfo = JsonConvert.DeserializeObject<WarningInfoEntity>(msg);
                    if (warningInfo != null)
                    {
                        DataController.InsertWarningInfo(warningInfo);
                    }
                }
            };
            App.server.Start();
        }
    }
}
